<?php


namespace App\Http\Middleware;


use App\Models\Customer;
use App\Models\CustomerUser;
use App\Models\Distribution;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class DistributionMiddleware
{
    /**
     * @param Request $request
     * @param Closure $next
     * @param mixed ...$guards
     * @return mixed
     */
    public function handle(Request $request, Closure $next, ...$guards)
    {
        $id = $request->route('distribution');

        $distribution = Distribution::query()->where('id', '=', $id)
            ->where('status', '=', 2)->first();

        if(empty($distribution)){
            throw new NotFoundHttpException('分销商不存在或者客户不可用');
        }

        $request->merge(['distribution_id' => $distribution->getKey()]);
        $request->route()->forgetParameter('distribution');

        /** @var CustomerUser $user */
        $user = auth('distribution')->user();
        // 是否有登录
        if ($user === null) {
            return $next($request);
        }
        if ($user->getAttribute('distribution_id') === $distribution->getKey()) {
            app()->instance('distribution', $distribution);
            return $next($request);
        }
        throw new NotFoundHttpException('请检查是杏存在这个用户！');
    }
}
